const dbName = "record";

const dbVersion = {
    key: "dbRecordVersion",

    init: function () {
        if ( localStorage.getItem( this.key ) === null )
        {
            localStorage.setItem( this.key, "0" );
        }
    },

    get: function () {
        return +localStorage.getItem( this.key );
    },

    increase: function () {
        let currentVersion = +localStorage.getItem( this.key );

        localStorage.setItem(
            this.key,
            ++currentVersion
        );
    }
};
dbVersion.init();

const database = {
    existenceTest: function () {
        return new Promise( function ( resolve, reject ) {
            dbVersion.increase();

            const request = indexedDB.open( dbName, dbVersion.get() );
        
            request.onerror = function ( event ) {
                reject( event.target.error );
        
                request.onerror = null;
            };
        
            request.onupgradeneeded = function ( event ) {console.log( "database.existenceTest: upgrade" );
                resolve();
        
                request.onupgradeneeded = null;
            };

            request.onclose = function () {
                console.log("close");
            };
        } );
    },

    createOS: function ( name, listOfIndexes ) {
        dbVersion.increase();

        const request = indexedDB.open( dbName, dbVersion.get() );

        request.onerror = function ( event ) {
            console.log( event.target.error );

            request.onerror = null;
        };

        request.onupgradeneeded = function ( event ) {console.log( "database.createOS: upgrade" );
            const db = event.target.result;

            db.createObjectStore( name, { autoIncrement: true } );

            request.onupgradeneeded = null;
        };
    }
};

export { database };